package com.baidu.fengchao.broad.action;

import com.baidu.fengchao.broad.bo.User;
import com.baidu.fengchao.broad.util.MD5Util;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Ok;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 * User: xiaojiangang
 * Date: 13-5-24
 * Time: 下午2:12
 */
@IocBean
@At("/user")
@Fail("json")
public class UserAction {
    private Dao dao;
    @At("/add")
    public int add(String email,String password,HttpServletResponse response){
        if(has(email) == 1){
            User user = new User();
            user.setEmail(email);
            user.setPassword(MD5Util.getMD5(password.getBytes()));
            dao.insert(user);
            write2Cookie(response,user);
            return 0;
        }else {
            return 1;
        }

    }

    //0 means pass
    @At("/login")
    @Ok("json")
    public int login(String email,String password,HttpServletResponse response){
        User user = dao.fetch(User.class, Cnd.where("email","=",email));
        if(null != user && user.getPassword().equals(MD5Util.getMD5(password.getBytes()))){
            write2Cookie(response,user);
            return 0;
        }else{
            return 1;
        }
    }

    //0 means have
    @At("has")
    @Ok("json")
    public int has(String email){
        return null == dao.fetch(User.class, Cnd.where("email","=",email))?1:0;
    }

    private void write2Cookie(HttpServletResponse response,Object obj){
        Cookie cookie = new Cookie("FCBROADID", Json.toJson(obj));
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}
